<template>
  <div class="login">
    <common-header></common-header>
    <div class="banner">
      <el-tabs class="left-tabs" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="密码登录" name="first">
          <el-form class="login-user" :model="loginUser" ref="loginUser" :rules="rules">
            <el-form-item label="" prop="account">
              <el-input type="text" v-model.lazy="loginUser.account" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="" prop="password">
              <el-input type="password" v-model.lazy="loginUser.password" placeholder="请输入密码"> </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="success" align="center" @click="loginUserForm('loginUser')">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="验证码登录" name="second">
          <el-form class="login-email login-user" :model="loginEmail" ref="loginEmail" :rules="rules">
            <el-form-item label="" prop="account">
              <el-input type="text" v-model.lazy="loginEmail.account" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="" prop="code" class="code-input">
              <el-input v-model.lazy="loginEmail.code" placeholder="请输入验证码"> </el-input>
              <button class="code" :disabled="timeCode.disabled" @click="getCode">{{ timeCode.txt }}</button>
            </el-form-item>
            <el-form-item>
              <el-button type="success" align="center" @click="loginEmailForm('loginEmail')">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <div class="login-label">
          <div class="left" @click="registerClick">注册</div>
          <div class="left" @click="getPassword">找回密码</div>
        </div>
      </el-tabs>
    </div>
    <!-- 图形验证码的弹框 -->
    <el-dialog title="图形验证码" :visible.sync="dialogImg" :close-on-click-modal="false" :modal-append-to-body="false">
      <img class="httpImg" @click="httpImgClick" :src="httpImg" alt="Img" />
      <el-form :rules="rules">
        <el-form-item label="">
          <el-input v-model="imgCode"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImg = false" style="width:100px">取 消</el-button>
        <el-button type="primary" @click="dialogImgClick" style="width:100px;margin-left:30px">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CommonHeader from '../../common/commonHeader'
export default {
  name: 'Login',
  components: {
    CommonHeader
  },
  data() {
    var validateUser = (rule, value, callback) => {
      // 验证账号
      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else {
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      // 验证密码
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 8) {
        callback(new Error('密码长度不得小于8位！'))
      }
      callback()
    }
    var validateEmail = (rule, value, callback) => {
      // 验证邮箱
      if (value === '') {
        callback(new Error('请正确填写邮箱'))
      } else if (!/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
        callback(new Error('请输入有效的邮箱'))
      } else {
        callback()
      }
    }
    var validateCode = (rule, value, callback) => {
      // 验证验证码
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      activeName: 'first',
      loginUser: {
        account: '',
        password: ''
      },
      loginEmail: {
        account: '',
        code: ''
      },
      timeCode: {
        // 短信验证码
        txt: '获取验证',
        time: 60,
        disabled: false
      },
      rules: {
        account: [{ validator: validateUser, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        email: [{ validator: validateEmail, trigger: 'blur' }],
        code: [{ validator: validateCode, trigger: 'blur' }]
      },
      // 图形弹框
      dialogImg: false,
      imgCode: '',
      httpImg: ''
    }
  },
  methods: {
    handleClick(tab) {
      console.log(tab)
    },
    // 账号密码登录
    loginUserForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log(this.loginUser.account + ',' + this.loginUser.password)
          const login = JSON.stringify(this.loginUser)
          // console.log(login)
          this.http
            .post('/web/login/account-login', login)
            .then(res => {
              console.log(res)
              if (res.result_code == '0') {
                this.$router.push('/console/consoleHome')
                this.$store.commit('getloginList', res.data)
                this.$store.commit('loginShow')
              } else {
                this.$message({
                  message: res.result_message,
                  type: 'error'
                })
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 邮箱登录
    loginEmailForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log(this.loginUser.account + ',' + this.loginUser.code)
          const email = JSON.stringify(this.loginEmail)
          // console.log(email)
          this.http
            .post('web/login/code-login', email)
            .then(res => {
              console.log(res)
              if (res.result_code == '0') {
                this.$router.push('/console.consoleHome')
                this.$store.commit('getloginList', res.data)
                this.$store.commit('loginShow')
              } else if (res.result_code == '4003') {
                this.$message({
                  message: res.result_message,
                  type: 'error'
                })
              } else {
                this.$message({
                  message: '账号或验证码错误！',
                  type: 'error'
                })
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          this.$message({
            message: '登录失败！',
            type: 'error'
          })
          return false
        }
      })
    },
    registerClick() {
      this.$router.push('/regsiter')
    },
    getPassword() {
      this.$router.push('/modify')
    },
    // 获取验证码操作
    async getCode() {
      console.log(this.loginEmail.account)
      var str = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (this.loginEmail.account == '') {
        // 验证码发送消息提示
        this.$message({
          message: '请正确填写邮箱',
          type: 'error'
        })
        return false
      } else if (!str.test(this.loginEmail.account)) {
        // 验证码发送消息提示
        this.$message({
          message: '请正确填写邮箱',
          type: 'error'
        })
        return false
      } else {
        // 先获取图形验证码
        this.dialogImg = true
        const num = Math.ceil(Math.random() * 100)
        // 图片流转base64
        const data = await this.http.get(`/web/login/get-captcha?${num}`, { responseType: 'arraybuffer' })
        console.log(data)
        this.httpImg = 'data:image/png;base64,' + btoa(new Uint8Array(data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        // console.log(this.httpImg)
      }
    },
    timeCodes() {
      // 验证码倒计时
      if (this.timeCode.time > 0) {
        this.timeCode.disabled = true
        this.timeCode.txt = this.timeCode.time + 's'
        this.timeCode.time--
      } else {
        this.timeCode.disabled = false
        this.timeCode.txt = '重新获取'
        this.timeCode.time = 60
        return
      }
      setTimeout(() => {
        this.timeCodes()
      }, 1000)
    },
    // 点击刷新图形验证码(用随机数触发)
    async httpImgClick() {
      const num = Math.ceil(Math.random() * 100)
      const data = await this.http.get(`/web/login/get-captcha?${num}`, { responseType: 'arraybuffer' })
      this.httpImg = 'data:image/png;base64,' + btoa(new Uint8Array(data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
    },
    // 获取验证码
    async dialogImgClick() {
      if (this.imgCode) {
        const codes = {
          account: this.loginEmail.account,
          send_code_type: 0,
          graph_code: this.imgCode
        }
        const codeList = JSON.stringify(codes)
        const data = await this.http.post('/web/login/send-code', codeList)
        if (data.result_code == '0') {
          this.imgCode = '' // 清空验证码
          this.dialogImg = false
          this.$message({
            message: '验证码发送成功！',
            type: 'success'
          })
          // 获取验证码
          this.timeCodes()
        } else {
          // 刷新验证码
          this.$message({
            message: data.result_message,
            type: 'error'
          })
          const num = Math.ceil(Math.random() * 100)
          const datas = await this.http.get(`/web/login/get-captcha?${num}`, { responseType: 'arraybuffer' })
          this.httpImg = 'data:image/png;base64,' + btoa(new Uint8Array(datas).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  @import '~@/assets/css/common.scss';
  background: url('~@/assets/images/home/home-banner.png') no-repeat;
  background-size: cover;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .banner {
    margin-right: 10%;
    /deep/.el-tabs {
      padding: 20px 50px 50px;
      background: #ffffff;
      box-sizing: border-box;
      border-radius: 5px;
    }
    /deep/.el-tabs__item {
      color: #a6a6a6;
      padding: 0 19%;
    }
    /deep/.el-tabs__item.is-active {
      color: #333333;
      padding: 0 19%;
    }
    /deep/.el-tabs__active-bar {
      background-color: $background;
      padding: 0 120px;
      left: -99px;
    }
    /deep/.el-tabs__nav {
      // padding: 10px 100px;
      width: 450px;
    }
    /deep/.el-button {
      width: 100%;
      background: $background;
      font-size: 14px;
      padding: 3%;
      letter-spacing: 2px;
      margin-top: 3%;
    }
    /deep/.el-input__inner {
      padding: 1.2% 0 1.2% 2%;
      font-size: 14px;
    }
  }
  .left-tabs {
    .login-user {
      margin-top: 30px;
    }
  }
  .login-label {
    display: flex;
    justify-content: space-between;
    color: $background;
    div {
      cursor: pointer;
    }
  }
  .code-input {
    width: 60%;
    .code {
      border: 1px solid #dcdfe6;
      background: transparent;
      color: #dcdfe6;
      border-radius: 4px;
      width: 155px;
      padding: 12px;
      position: absolute;
      right: -66%;
      top: -3%;
      cursor: pointer;
    }
  }
}
// 图形验证码
.httpImg {
  width: 160px;
  margin-bottom: 10px;
  cursor: pointer;
}
/deep/.el-dialog {
  text-align: center;
  width: 30%;
  .el-dialog__body {
    padding: 20px 100px 0;
    .el-input__inner {
      text-align: center;
    }
  }
  .el-button--default:hover {
    background: #fff;
    color: #23b769;
    border: 1px solid #23b769;
  }
  .el-button--primary:focus,
  .el-button--primary:hover {
    background: #23b769;
    color: #ffffff;
  }
  .el-dialog__footer {
    text-align: center;
  }
}
</style>
